<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="药品全称" prop="fullName">
        <el-input
          v-model="queryParams.fullName"
          placeholder="请输入全称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品简称" prop="shorterName">
        <el-input
          v-model="queryParams.shorterName"
          placeholder="请输入简称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品规格" prop="specs">
        <el-input
          v-model="queryParams.specs"
          placeholder="请输入规格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品类型">
        <el-select clearable v-model="queryParams.drugType" placeholder="请选择药品类型">
          <el-option v-for="dict in drugTypeOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="状态" prop="flag">
        <el-select v-model="queryParams.flag" placeholder="请选择状态">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>-->
      <!--<el-form-item label="创建时间" prop="createDate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.createDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间" prop="updateDate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.updateDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择修改时间">
        </el-date-picker>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          :disabled="multiple"
          v-hasPermi="['drugs:drugsQuery:addOrder']"
        >新增订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addDrugs"
          v-hasPermi="['drugs:drugsQuery:addDrugs']"
        >新增药品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="putOnShelf"
          v-hasPermi="['drugs:drugsQuery:putOnShelf']"
        >上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="offShelf"
          v-hasPermi="['drugs:drugsQuery:offShelf']"
        >下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['drugs:drugsQuery:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['drugs:drugsQuery:remove']"
        >删除</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="drugsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="全称" :show-overflow-tooltip="true" align="center" prop="fullName" />
      <el-table-column label="简称" :show-overflow-tooltip="true" align="center" prop="shorterName" />
      <el-table-column label="药品类型" :show-overflow-tooltip="true" align="center" :formatter="drugTypeFormat" />
      <el-table-column label="商品图" align="center" prop="pimage" >
      <template slot-scope="scope">
        <img  min-width="100" height="100" :src="scope.row.pimage"/>
      </template>
      </el-table-column>
      <el-table-column label="规格" :show-overflow-tooltip="true" align="center" prop="specs" />
      <el-table-column label="适应症" :show-overflow-tooltip="true" align="center" prop="adapt" />
      <el-table-column label="特点" :show-overflow-tooltip="true" align="center" prop="trait" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column v-if="userRole" label="是否上架" align="center" prop="isShelves">
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.isShelves == 1">上架</span>
          <span style="color: red" v-if="scope.row.isShelves == 2">下架</span>
        </template>
      </el-table-column>
      <el-table-column v-if="userRole" label="是否自营" align="center" prop="isSelf" >
      <template slot-scope="scope">
        <span style="color: green" v-if="scope.row.isSelf == 1">自营</span>
        <span style="color: red" v-if="scope.row.isSelf == 2">非自营</span>
      </template>
      </el-table-column>

      <!--<el-table-column label="状态" align="center" prop="flag" :formatter="stateFormat" />-->
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUser" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showProductInfo(scope.row)"
          >产品详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['drugs:drugsQuery:edit']"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['drugs:drugsQuery:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加订单 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px"  append-to-body>
      <el-table v-loading="loading" :data="drugsOrderList" @selection-change="handleSelectionChange">
        <el-table-column label="全称" :show-overflow-tooltip="true" align="center" prop="fullName" />
        <el-table-column label="简称" :show-overflow-tooltip="true" align="center" prop="shorterName" />
        <el-table-column label="商品图":show-overflow-tooltip="true" align="center" prop="pimage" >
          <template slot-scope="scope">
            <img min-width="50" height="50" :src="scope.row.pimage"/>
          </template>
        </el-table-column>
        <el-table-column label="规格":show-overflow-tooltip="true" align="center" prop="specs" />
        <el-table-column label="适应症" :show-overflow-tooltip="true" align="center" prop="adapt" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="数量" align="center" width="220px" prop="num" >
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.num" :min="1"  label="描述文字"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteOrder(scope.row)"

            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--<pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handleAdd"
      />-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrder">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加订单 -->
    <el-dialog :title="title" :visible.sync="openProductInfo" width="1000px"  append-to-body>
      <div v-html="productInfo" ></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelInfo">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDrugs, getDrugs, delDrugs, updateDrugs,queryDrugsIds,addOrder,updateIsShelves  } from "@/api/drugs/drugs";

  export default {
    name: "Drugs",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        options: [{
          value: '0',
          label: '有效'
        }, {
          value: '1',
          label: '无效'
        }],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 【药品】表格数据
        drugsList: [],
        //要添加到订单的药品
        drugsOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //显示产品详情
        openProductInfo:false,
        //产品详情html
        productInfo:'',
        userRole:false,
        drugTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fullName: undefined,
          shorterName: undefined,
          pimage: undefined,
          specs: undefined,
          adapt: undefined,
          trait: undefined,
          productInfo: undefined,
          flag: undefined,
          createDate: undefined,
          updateDate: undefined,
          createUser: undefined,
          updateUser: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          fullName: [
            { required: true, message: "全称不能为空", trigger: "blur" }
          ],
          flag: [
            { required: true, message: "状态：0有效，1无效不能为空", trigger: "blur" }
          ],
          createDate: [
            { required: true, message: "创建时间不能为空", trigger: "blur" }
          ],
          updateDate: [
            { required: true, message: "修改时间不能为空", trigger: "blur" }
          ],
          createUser: [
            { required: true, message: "创建人不能为空", trigger: "blur" }
          ],
          updateUser: [
            { required: true, message: "修改人不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getDicts('drug_type').then(response => {
        this.drugTypeOptions = response.data
      });

      this.getList();

    },
    methods: {
      drugTypeFormat(row, column) {
        return this.selectDictLabel(this.drugTypeOptions, row.drugType);
      },

      stateFormat(row, column) {
        if (row.flag == 0) {
          return '有效'
        } else {
          return '无效'
        }
      },
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        listDrugs(this.queryParams).then(response => {
          this.drugsList = response.rows;
          if(response.rows[0] != undefined && response.rows[0].datacope != 5){
            this.userRole = true;
          }else{
            this.userRole = false;
          }

          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      cancelInfo(){
        this.openProductInfo = false;
        this.reset();
      },
      //新增药品
      addDrugs(){
        this.$router.push('/drugs/drugsAdd');
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          fullName: undefined,
          shorterName: undefined,
          pimage: undefined,
          specs: undefined,
          adapt: undefined,
          trait: undefined,
          productInfo: undefined,
          flag: undefined,
          createDate: undefined,
          updateDate: undefined,
          createUser: undefined,
          updateUser: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增订单操作 */
      handleAdd(row) {
        this.reset();
        const id = row.id || this.ids

        this.title = "添加订单";

        queryDrugsIds(id).then(response => {
          if (response.code === 200) {
            this.open = true;

            for(var i = 0 ;i < response.rows.length;i++){
              var drugsOrder ={
                num:1,
                id:response.rows[i].id,
                fullName:response.rows[i].fullName,
                shorterName:response.rows[i].shorterName,
                pimage:response.rows[i].pimage,
                specs:response.rows[i].specs,
                adapt:response.rows[i].adapt,
                trait:response.rows[i].trait,
                price:response.rows[i].price,
                productInfo:response.rows[i].productInfo,
                flag:response.rows[i].flag
              }
              var flag = true;
              for(var j = 0;j< this.drugsOrderList.length;j++){
                if(this.drugsOrderList[j].id == drugsOrder.id){
                  this.drugsOrderList[j].num ++;
                  flag = false;
                }
              }
              if(flag){
                this.drugsOrderList.push(drugsOrder);
              }

            }

          } else {
            this.msgError(response.msg);
          }
        });
      },
      /** 修改按钮操作 */
      showProductInfo(row) {
        this.reset();
        this.openProductInfo = true;
        this.title="产品详情"
        this.productInfo = row.productInfo;

      },
      //上架
      putOnShelf(){
        var ids = this.ids
        updateIsShelves(ids,1).then(response => {
          this.msgSuccess(response.msg);
          this.getList();
        });

      },
      //下架
      offShelf(){
        var ids = this.ids
        updateIsShelves(ids,2).then(response => {
          this.msgSuccess(response.msg);
          this.getList();
        });
      },
      /** 添加订单 */
      addOrder: function() {
        const sumOrdrs ={
        remark:undefined,
        tOrder:[]
        };
        const orders = [];
        for(var i = 0; i < this.drugsOrderList.length; i++){
          const order = {
            drugsId: undefined,
            number: undefined
          };
          const remark=
          order.drugsId = this.drugsOrderList[i].id;
          order.number = this.drugsOrderList[i].num;
          order.orderPrice = this.drugsOrderList[i].num * this.drugsOrderList[i].price;
          orders.push(order);
        }
        if(orders.length < 1){
          this.msgSuccess("请选择药品");
          return;
        }
        sumOrdrs.remark = '';
        sumOrdrs.tOrder = orders;
        addOrder(sumOrdrs).then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg);
            this.open = false;
            this.drugsOrderList = [];
            this.getList();
          }else{
            this.msgError(response.msg);
          }
        });
      },
      //删除未添加订单
      deleteOrder(row) {
        const id = row.id;
        for(var i = 0;i < this.drugsOrderList.length;i++){
          if(id == this.drugsOrderList[i].id){
            this.drugsOrderList.splice(i,1);
          }
        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDrugs(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      //修改
      handleUpdate(row){
        const id = row.id || this.ids[0];
        this.$router.push({path:'/drugs/drugsAdd',query:{id:id}});

      },

    }
  };
</script>
